package com.example.wangda.smarthome_pad_host;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
    /*聚合数据 获取天气 json格式数据*/
    private PureNetUtil weather_get;
    /*UDP网络连接用的SOCKET*/
    private DatagramSocket socketUDP = null;
    /*控件 CHECK*/
    private CheckBox doorOnlyCB;
    private CheckBox stairsOnlyCB;
    private CheckBox outTwoOnlyCB;
    private CheckBox twoBedroomOnlyCB;
    /*控件 BUTTON*/
    private Switch outTwoLightSwitch;
    private Switch twoBedroomLightSwitch;
    private Switch stairsLightSwitch;
    private Switch allLightSwitch;
    /*线程 创建*/
    private Thread musicThread = null;
    private Thread udpRecvHandleThread = null;
    private Thread udpSendHandleThread = null;
    private Thread timeThread = null;
    /*控件 text_view*/
    private TextView info_text;
    private TextView time_text;
    /*控件 EDITTEXT*/
    private EditText stairs_delay;
    private EditText twoout_delay;
    private EditText door_delay;
    private EditText bed_delay;

    /*UDP接收到的数据临时存储*/
    private char recvDataSourAddr = 0;        //接收到的数据的原地址
    private char recvDataSourChannel = 0;     //接收到的数据的源通道
    private char recvDataCtrlCmd = 0;         //接收到的数据的命令
    private char recvDataCtrlPara = 0;        //接收到的数据命令后面的参数
    /*延时计数变量定义*/
    private int inDoorIntCount = 0;   //进门事件延时
    private int stairsIntCount = 0;   //楼梯灯光延时
    private int twoBedIntCount = 0;    //二楼卧室灯光延时
    private int twoOutIntCount = 0;    //二楼外侧灯光延时

    private int doorOnlyCount=extern_define.DEVICEONLYDELAY;  //设备不在线超时计数
    private int stairsOnlyCount=extern_define.DEVICEONLYDELAY;
    private int outTwoOnlyCount=extern_define.DEVICEONLYDELAY;
    private int twoBedOnlyCount=extern_define.DEVICEONLYDELAY;
    /*手动&自动模式切换状态标识*/
    private char doorManulstatus = 0; //门口手动模式状态
    private char stairManulstatus = 0; //楼道手动模式状态
    private char outtwoManulstatus = 0; //二楼外侧手动模式状态
    private char twobedManulstatus = 0; //二楼卧室手动模式状态
    /*Handle 创建*/
    private Handler musicHandler;
    private Handler udpSendHandler;
    /*各位置触发计数*/
    private int doorTrigCount=0;
    private int stairsTrigCount=0;
    private int outTwoTrigCount=0;
    private int twoBedTrigCount=0;
    //TTS
    private SpeechSynthesizer mTts;
    private int current_hour = 0;  //当前的小时值
    //YEELIGHT
    private String TAG = "Control";

    private static final int MSG_CONNECT_SUCCESS = 0;
    private static final int MSG_CONNECT_FAILURE = 1;
    private static final String CMD_TOGGLE = "{\"id\":%id,\"method\":\"toggle\",\"params\":[]}\r\n" ;
    private static final String CMD_ON = "{\"id\":%id,\"method\":\"set_power\",\"params\":[\"on\",\"smooth\",1500]}\r\n" ;
    private static final String CMD_OFF = "{\"id\":%id,\"method\":\"set_power\",\"params\":[\"off\",\"smooth\",1500]}\r\n" ;
    private static final String CMD_CT = "{\"id\":%id,\"method\":\"set_ct_abx\",\"params\":[%value, \"smooth\", 500]}\r\n";
    private static final String CMD_HSV = "{\"id\":%id,\"method\":\"set_hsv\",\"params\":[%value, 100, \"smooth\", 200]}\r\n";
    private static final String CMD_BRIGHTNESS = "{\"id\":%id,\"method\":\"set_bright\",\"params\":[%value, \"smooth\", 200]}\r\n";
    private static final String CMD_BRIGHTNESS_SCENE = "{\"id\":%id,\"method\":\"set_bright\",\"params\":[%value, \"smooth\", 500]}\r\n";
    private static final String CMD_ATUO_OFF_SCENE = "{\"id\":%id,\"method\":\"set_scene\",\"params\":[\"auto_delay_off\",100,%tm]}\r\n";

    private int mCmdId;
    private Socket mSocket;
    private BufferedOutputStream mBos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tts_init();
        netword_connect();
        widget_init();

        info_text.setKeepScreenOn(true);   //屏幕常量
        thread_creation();
        buttonHandleFunc();
    }

    /*函数作用 延时计数变量根据设定值初始化*/
//    private void delay_variant_init()
//    {
//        extern_define.DOORDELAY = Integer.parseInt(door_delay.getText().toString());
//        inDoorIntCount = extern_define.DOORDELAY;
//        extern_define.STAIRSDELAY = Integer.parseInt(stairs_delay.getText().toString());
//        stairsIntCount = extern_define.STAIRSDELAY;
//        extern_define.TWOBEDDELAY = Integer.parseInt(bed_delay.getText().toString());
//        twoBedIntCount = extern_define.TWOBEDDELAY;
//        extern_define.TWOOURDELAY = Integer.parseInt(twoout_delay.getText().toString());
//        twoOutIntCount = extern_define.TWOOURDELAY;
//    }
    /*讯飞TTS*/
    private void tts_init()
    {
        // 将“12345678”替换成您申请的 APPID，申请地址： http://www.xfyun.cn
        // 请勿在“ =”与 appid 之间添加任务空字符或者转义符
        SpeechUtility.createUtility(MainActivity.this, SpeechConstant.APPID +"=58eaf86e");
        //1.创建 SpeechSynthesizer 对象, 第二个参数： 本地合成时传 InitListener
        mTts= SpeechSynthesizer.createSynthesizer(MainActivity.this, null);
        //2.合成参数设置，详见《 MSC Reference Manual》 SpeechSynthesizer 类
        //设置发音人（更多在线发音人，用户可参见 附录13.2
        mTts.setParameter(SpeechConstant.VOICE_NAME, "aisjiuxu"); //设置发音人
        mTts.setParameter(SpeechConstant.SPEED, "60");//设置语速
        mTts.setParameter(SpeechConstant.VOLUME, "100");//设置音量，范围 0~100
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置云端
        //设置合成音频保存位置（可自定义保存位置），保存在“./sdcard/iflytek.pcm”
        //保存在 SD 卡需要在 AndroidManifest.xml 添加写 SD 卡权限
        //仅支持保存为 pcm 和 wav 格式， 如果不需要保存合成音频，注释该行代码
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, "./sdcard/iflytek.pcm");
        //3.开始合成

        Log.i("DEBUG", "科大讯飞tts初始化");
    }
    //合成监听器
    private SynthesizerListener mSynListener = new SynthesizerListener(){
        //会话结束回调接口，没有错误时， error为null
        public void onCompleted(SpeechError error) {}
        //缓冲进度回调
        //percent为缓冲进度0~100， beginPos为缓冲音频在文本中开始位置， endPos表示缓冲音频在
       // 文本中结束位置， info为附加信息。
        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {}
        //开始播放
        public void onSpeakBegin() {}
        //暂停播放
        public void onSpeakPaused() {}
        //播放进度回调
        //percent为播放进度0~100,beginPos为播放音频在文本中开始位置， endPos表示播放音频在文
        //本中结束位置.
        public void onSpeakProgress(int percent, int beginPos, int endPos) {}
        //恢复播放回调接口
        public void onSpeakResumed() {}
        //会话事件回调接口
        public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {}

        public void onError(SpeechError error) {
            Log.i("DEBUG", error.toString());
        }
    };


    /*函数作用：网络链接*/
    private void netword_connect()
    {
        try {
            /*设定本地端口号*/
            socketUDP = new DatagramSocket(Integer.parseInt(this.getString(R.string.network_sour_port)));
            Log.i("DEBUG", "本地端口号" + Integer.parseInt(this.getString(R.string.network_sour_port)));
            Log.i("DEBUG", "网络连接初始化");

            Log.i("DEBUG", "聚合数据 天气数据类定义");
        }catch(Exception e)
        {
            Log.i("DEBUG", "netword_connect try error" + e.toString());
        }
    }
    /*函数作用：控件初始化*/
    private void widget_init()
    {
        outTwoLightSwitch = (Switch)findViewById(R.id.widget_outTwoLightSw);
        twoBedroomLightSwitch = (Switch)findViewById(R.id.widget_twoBedroomLightSw);
        stairsLightSwitch = (Switch)findViewById(R.id.widget_stairsLightSw);
        allLightSwitch = (Switch)findViewById(R.id.widget_allightSw);

        doorOnlyCB = (CheckBox)findViewById(R.id.widget_doorCk);
        stairsOnlyCB = (CheckBox)findViewById(R.id.widget_stairsCk);
        outTwoOnlyCB = (CheckBox)findViewById(R.id.widget_twoOutCk);
        twoBedroomOnlyCB = (CheckBox)findViewById(R.id.widget_twoBedroomCk);

        info_text = (TextView)findViewById(R.id.info_view);
        time_text = (TextView)findViewById(R.id.time_view);

        stairs_delay = (EditText) findViewById(R.id.edit_text_stairsDelay);
        twoout_delay = (EditText) findViewById(R.id.edit_text_twoout);
        door_delay = (EditText) findViewById(R.id.edit_text_door);
        bed_delay = (EditText) findViewById(R.id.edit_text_bed);

        Log.i("DEBUG", "控件初始化");
    }

    /*函数作用： YEELIGHT初始化*/
    private void yeelight_init()
    {
        try {
            mSocket = new Socket("192.168.123.105", 55443);
            mSocket.setKeepAlive(true);
            mBos = new BufferedOutputStream(mSocket.getOutputStream());
        }catch (Exception e)
        {
            Log.i("ERROR","yeelight_init error"+ e.toString());
        }
    }
    //yeelight
    private void write(String cmd){
        if (mBos != null && mSocket.isConnected()){
            try {
                mBos.write(cmd.getBytes());
                mBos.flush();
            }catch (Exception e){
                e.printStackTrace();
            }
        } else {
            Log.d(TAG,"mBos = null or mSocket is closed");
        }
    }
    private String parseSwitch(boolean on){
        String cmd;
//        if (on){
//            cmd = CMD_ON.replace("%id", String.valueOf(++mCmdId));
//        }else {
//            //cmd = CMD_OFF.replace("%id", String.valueOf(++mCmdId));
//        }
        cmd = CMD_ATUO_OFF_SCENE.replace("%id", String.valueOf(++mCmdId));
        cmd = cmd.replace("%tm", bed_delay.getText().toString());
        return cmd;
    }

    /*函数作用：线程创建*/
    private void thread_creation()
    {
        try {
            musicThread = new Thread(musicHandleFunc);
            udpRecvHandleThread = new Thread(udpRecvHandleFunc);
            udpSendHandleThread = new Thread(udpSendHandleFunc);
            timeThread = new Thread(timeHandleFunc);

            musicThread.start();
            udpRecvHandleThread.start();
            udpSendHandleThread.start();
            timeThread.start();
        }catch (Exception e)
        {
            Log.i("DEBUG", "thread_creation try error " + e.toString());
        }
        Log.i("DEBUG", "线程初始化");
    }

    /*函数作用：按键动作响应函数*/
    private void buttonHandleFunc()
    {
        outTwoLightSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if(isChecked)
                {
                    Message toMusicHandle = new Message();
                    toMusicHandle.arg1 = extern_define.UDPSENDOUTTWOLIGHTSET;
                    udpSendHandler.sendMessage(toMusicHandle);
                    Toast.makeText(getApplicationContext(), "二楼外侧灯光延打开", Toast.LENGTH_SHORT).show();
                   // outtwoManulstatus = extern_define.MANULOPEN;
                }
                else
                {
                    Message toUdpSendHandle1 = new Message();
                    toUdpSendHandle1.arg1 = extern_define.UDPSENDOUTTWOLIGHTRESET;
                    udpSendHandler.sendMessage(toUdpSendHandle1);
                    Toast.makeText(getApplicationContext(), "二楼外侧灯光延关闭", Toast.LENGTH_SHORT).show();
                   // outtwoManulstatus = extern_define.MANULAUTO;
                }
            }
        });

        twoBedroomLightSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if(isChecked)
                {
                    Message toUdpSendHandle1 = new Message();
                    toUdpSendHandle1.arg1 = extern_define.UDPSENDTWOBEDROOMLIGHTSET;
                    udpSendHandler.sendMessage(toUdpSendHandle1);
                    Toast.makeText(getApplicationContext(), "二楼卧室灯光延打开", Toast.LENGTH_SHORT).show();
                    //twobedManulstatus = extern_define.MANULOPEN;
                    if(current_hour>=8 && current_hour <= 23)
                    {
                        write(parseSwitch(true));
                    }
                }
                else
                {
                    Message toUdpSendHandle1 = new Message();
                    toUdpSendHandle1.arg1 = extern_define.UDPSENDTWOBEDROOMLIGHTRESET;
                    udpSendHandler.sendMessage(toUdpSendHandle1);
                    Toast.makeText(getApplicationContext(), "二楼卧室灯光延关闭", Toast.LENGTH_SHORT).show();
                    //twobedManulstatus = extern_define.MANULAUTO;
                    //write(parseSwitch(false));
                }
            }
        });

        stairsLightSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if(isChecked)
                {
                    Message toUdpSendHandle1 = new Message();
                    toUdpSendHandle1.arg1 = extern_define.UDPSENDSTAIRSLIGHTSET;
                    udpSendHandler.sendMessage(toUdpSendHandle1);
                    Toast.makeText(getApplicationContext(), "楼道灯光延打开", Toast.LENGTH_SHORT).show();
                    //stairManulstatus = extern_define.MANULOPEN;
                }
                else
                {
                    Message toUdpSendHandle1 = new Message();
                    toUdpSendHandle1.arg1 = extern_define.UDPSENDSTAIRSLIGHTRESET;
                    udpSendHandler.sendMessage(toUdpSendHandle1);
                    Toast.makeText(getApplicationContext(), "楼道灯光延关闭", Toast.LENGTH_SHORT).show();
                    //stairManulstatus = extern_define.MANULAUTO;
                }
            }
        });

        allLightSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if(isChecked)
                {
                    stairsLightSwitch.setChecked(true);
                    outTwoLightSwitch.setChecked(true);
                    twoBedroomLightSwitch.setChecked(true);
                    Toast.makeText(getApplicationContext(), "所有灯光延打开", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    stairsLightSwitch.setChecked(false);
                    outTwoLightSwitch.setChecked(false);
                    twoBedroomLightSwitch.setChecked(false);
                    Toast.makeText(getApplicationContext(), "所有灯光延关闭", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private Runnable musicHandleFunc = new Runnable() {
        @Override
        public void run() {
            final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.test); //欢迎光临
            final MediaPlayer yzcw = MediaPlayer.create(getApplicationContext(), R.raw.yvzouchangwan); //渔舟唱晚
            final MediaPlayer go_home = MediaPlayer.create(getApplicationContext(), R.raw.gohome); //回家
            while (true) {
                Looper.prepare();
                musicHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        /*ps:晚上9点以后到第二天早上7点，进门不播放*/
                        if (msg.arg1 == extern_define.PROTOCOL_HANDLE_DOOR_MANSENSER && (current_hour >= 7) && (current_hour <= 20)) {
                            //Toast.makeText(MainActivity.this, "门口人体感应事件处理", Toast.LENGTH_SHORT);
                            mp.start();
                            Log.i("log", "musicHandle" + msg.arg1);
                        }
                        if (msg.arg1 == extern_define.PROTOCOL_MUSIC_YZCW) {
                            yzcw.start();
                            Log.i("log", "musicHandle" + msg.arg1);
                        }
                        if(msg.arg1 == extern_define.PROTOCOL_MUSIC_GOHOME){
                            go_home.start();
                            Log.i("log", "musicHandle" + msg.arg1);
                        }
                        if(msg.arg1 == extern_define.PROTOCOL_GET_WEATHER)
                        {
                            mp.start();
                            /*注意 同一时间讯飞语音播放只能一处调用，否则会导致异常*/
                            weather_get = new PureNetUtil();
                            String weather_data = weather_get.get("http://v.juhe.cn/weather/index?cityname=%E5%AE%81%E6%B3%A2&dtype=&format=&key=fedd6211b2e5dcda943f92e3318e425f");
                            Log.i("TEXT", "天气数据 = " + weather_data);
                            mTts.startSpeaking("现在是早上7点钟, 早上好：" + weather_get.parse_json(weather_data), mSynListener);
                        }
                    }
                };
                Looper.loop();
            }
        }
    };

    private Runnable udpRecvHandleFunc = new Runnable() {
        /*存储UDP接收到的源数据*/
        byte udpRecvBuf[] = new byte[1024];
        /*存储转换后的16进制数据*/
        char hexData[] = new char[1024];
        @Override
        public void run() {
            yeelight_init();
            while(true)
            {
                try {
                    DatagramPacket packetR = new DatagramPacket(udpRecvBuf, udpRecvBuf.length);
                    socketUDP.receive(packetR);
                }catch(Exception e)
                {
                    Log.i("DEBUG", "udpRecvHandleFunc try error" + e.toString());
                }
                for (int i = 0; i < udpRecvBuf.length; i++)  //将收到的数据全部转换为无符号数
                {
                    hexData[i] = (char) (udpRecvBuf[i] & 0xFF);
                }
                Log.i("DEBUG", "UDP 接收到数据");
                if (extern_define.PROTOCOL_START == (char) hexData[extern_define.PROTOCOL_NAME_START]) {
                    if (hexData[extern_define.PROTOCOL_NAME_DESTADDR] == extern_define.PROTOCOL_BOX_ADDR) {
                        if (hexData[extern_define.PROTOCOL_NAME_DEVICES_TYPE] == extern_define.PROTOCOL_DEVICES_TYPE) {
                            recvDataSourAddr = hexData[extern_define.PROTOCOL_NAME_SOURADDR];
                            recvDataSourChannel = hexData[extern_define.PROTOCOL_NAME_SOURCHANNEL];
                            recvDataCtrlCmd = hexData[extern_define.PROTOCOL_NAME_CMD];
                            recvDataCtrlPara = hexData[extern_define.PROTOCOL_NAME_CMD + 1];
                            switch (recvDataCtrlCmd) {
                                case extern_define.PROTOCOL_CMD_QUERY:
                                    //TODO 查询命令
                                    break;

                                case extern_define.PROTOCOL_CMD_MOSSET:
                                    //TODO MOS设置
                                    break;

                                case extern_define.PROTOCOL_CMD_BREATHE:      //呼吸包
                                    if (recvDataSourAddr == extern_define.PROTOCOL_LOCAT_DOOR)  //门口
                                    {
                                        Message DeviceOnlySetHandle = new Message();
                                        DeviceOnlySetHandle.arg1 = extern_define.DOORDEVICECHECKBOXSET;
                                        deviceOnlyCheckBoxSet.sendMessage(DeviceOnlySetHandle);
                                        doorOnlyCount = 0;
                                        doorOnlyCount=extern_define.DEVICEONLYDELAY;
                                        Log.i("log", "收到UDP呼吸包，位置为：门口");
                                    }
                                    else if(recvDataSourAddr == extern_define.PROTOCOL_LOCAT_STAIRS)   //楼道
                                    {
                                        Message DeviceOnlySetHandle = new Message();
                                        DeviceOnlySetHandle.arg1 = extern_define.STAIRSDEVICECHECKBOXSET;
                                        deviceOnlyCheckBoxSet.sendMessage(DeviceOnlySetHandle);
                                        stairsOnlyCount = 0;
                                        stairsOnlyCount=extern_define.DEVICEONLYDELAY;
                                        Log.i("log", "收到UDP呼吸包，位置为：楼道");
                                    }
                                    else if(recvDataSourAddr == extern_define.PROTOCOL_LOCAT_TWOOUT) //二楼外面
                                    {
                                        Message DeviceOnlySetHandle = new Message();
                                        DeviceOnlySetHandle.arg1 = extern_define.OUTTWODEVICECHECKBOXSET;
                                        deviceOnlyCheckBoxSet.sendMessage(DeviceOnlySetHandle);
                                        outTwoOnlyCount = 0;
                                        outTwoOnlyCount=extern_define.DEVICEONLYDELAY;
                                        Log.i("log", "收到UDP呼吸包，位置为：二楼外面");
                                    }
                                    else if(recvDataSourAddr == extern_define.PROTOCOL_LOCAL_TWOSLEEP)   //二楼卧室
                                    {
                                        Message DeviceOnlySetHandle = new Message();
                                        DeviceOnlySetHandle.arg1 = extern_define.TWOBEDROOMDEVICECHECKBOXSET;
                                        deviceOnlyCheckBoxSet.sendMessage(DeviceOnlySetHandle);
                                        twoBedOnlyCount = 0;
                                        twoBedOnlyCount=extern_define.DEVICEONLYDELAY;
                                        Log.i("log", "收到UDP呼吸包，位置为：二楼卧室");
                                    }

                                    break;
                                case extern_define.PROTOCOL_CMD_SENSER:
                                    //TODO 判断通道几
                                    if (recvDataSourAddr == extern_define.PROTOCOL_LOCAT_DOOR)  //门口
                                    {
                                        if ((recvDataSourChannel == extern_define.PROTOCOL_DOOR_MANSENSER_NUM ) && (doorManulstatus == extern_define.MANULAUTO))   //人体传感器
                                        {
                                            if(inDoorIntCount == 0) {
                                                Log.i("log", "doorSenserManHandleSend");
                                                Message toMusicHandle = new Message();
                                                toMusicHandle.arg1 = extern_define.PROTOCOL_HANDLE_DOOR_MANSENSER;
                                                musicHandler.sendMessage(toMusicHandle);
                                                doorTrigCount+=1;   //触发次数统计
                                            }/*TODO 记录下当前的时间 加上要延时的时间 判断时间是否到达*/
                                            inDoorIntCount = Integer.parseInt(door_delay.getText().toString());
                                        }
                                    }

                                    if (recvDataSourAddr == extern_define.PROTOCOL_LOCAT_STAIRS)    //楼道
                                    {
                                        if ((recvDataSourChannel == extern_define.PROTOCOL_STAIRS_MANSENSER_NUM) && (stairManulstatus == extern_define.MANULAUTO)) {
                                            Log.i("log", "tairsSenserManHandleSend");
                                            Message toUDPSendHandle = new Message();
                                            toUDPSendHandle.arg1 = extern_define.UDPSENDSTAIRSLIGHTSET;
                                            udpSendHandler.sendMessageDelayed(toUDPSendHandle, 0);

                                            Message todeviceLightSet = new Message();
                                            todeviceLightSet.arg1 = extern_define.UDPSENDSTAIRSLIGHTSET;
                                            deviceLightSet.sendMessageDelayed(todeviceLightSet, 0);

                                            stairsIntCount = Integer.parseInt(stairs_delay.getText().toString());
                                            stairsTrigCount+=1; //触发次数统计
                                        }
                                    }

                                    if(recvDataSourAddr == extern_define.PROTOCOL_LOCAT_TWOOUT) //二楼外面
                                    {
                                        if((recvDataSourChannel == extern_define.PROTOCOL_OUTTWO_MANSENSER_NUM) && (outtwoManulstatus == extern_define.MANULAUTO))
                                        {
                                            Log.i("log", "outtwosenserman HandleSend");
//                                            Message toMusicHandle = new Message();
//                                            toMusicHandle.arg1 = extern_define.PROTOCOL_HANDLE_OUTTWO_MANSENSER;
//                                            musicHandler.sendMessageDelayed(toMusicHandle, twoOutIntCount);

                                            Message toUDPSendHandle = new Message();
                                            toUDPSendHandle.arg1 = extern_define.UDPSENDOUTTWOLIGHTSET;
                                            udpSendHandler.sendMessageDelayed(toUDPSendHandle, 0);

                                            Message todeviceLightSet = new Message();
                                            todeviceLightSet.arg1 = extern_define.UDPSENDOUTTWOLIGHTSET;
                                            deviceLightSet.sendMessageDelayed(todeviceLightSet, 0);

                                            twoOutIntCount = Integer.parseInt(twoout_delay.getText().toString());
                                            outTwoTrigCount+=1; //触发次数统计
                                        }
                                    }

                                    if(recvDataSourAddr == extern_define.PROTOCOL_LOCAL_TWOSLEEP)     //二楼卧室
                                    {
                                        if((recvDataSourChannel == extern_define.PROTOCOL_TWOBEDROOM_MANSENSER_NUM) && (twobedManulstatus == extern_define.MANULAUTO))
                                        {
                                            Log.i("log", "twobedroomsenserman HandleSend");
                                            Message toUDPSendHandle = new Message();
                                            /*发送消息，开灯*/
                                            twoBedIntCount = Integer.parseInt(bed_delay.getText().toString());
                                            toUDPSendHandle.arg1 = extern_define.UDPSENDTWOBEDROOMLIGHTSET;
                                            udpSendHandler.sendMessage(toUDPSendHandle);

                                            Message todeviceLightSet = new Message();
                                            todeviceLightSet.arg1 = extern_define.UDPSENDTWOBEDROOMLIGHTSET;
                                            deviceLightSet.sendMessageDelayed(todeviceLightSet, 0);

                                            twoBedIntCount = Integer.parseInt(bed_delay.getText().toString());
                                            twoBedTrigCount+=1; //触发次数统计
                                        }
                                    }
                                    break;
                            }

                        }
                    }
                }
            }
        }
    };

    /*UDP发送函数*/
    private Runnable udpSendHandleFunc = new Runnable() {
        char data1[] = new char[11];
        byte sendBuf[] = new byte[11];
        @Override
        public void run() {
            while (true) {
                Looper.prepare();
                udpSendHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        data1[extern_define.PROTOCOL_NAME_START] = extern_define.PROTOCOL_START;
                        data1[extern_define.PROTOCOL_NAME_SOURADDR] = extern_define.PROTOCOL_BOX_ADDR;
                        data1[extern_define.PROTOCOL_NAME_SOURCHANNEL] = 0x01;
                        data1[extern_define.PROTOCOL_NAME_DEVICES_TYPE] = extern_define.PROTOCOL_DEVICES_TYPE;
                        data1[extern_define.PROTOCOL_NAME_DATA_LEN] = 0x03;
                        super.handleMessage(msg);
                        Log.i("log", "udpSendHandler enter " + msg.arg1);
                        try {
                            switch (msg.arg1)
                            {
                                case extern_define.UDPSENDBREATHEPACK:    //呼吸包
                                    data1[extern_define.PROTOCOL_NAME_DESTADDR] = extern_define.PROTOCOL_DEVICEBROAD_ADDR;
                                    data1[extern_define.PROTOCOL_NAME_DESTCHANNEL] = 0x01;
                                    data1[extern_define.PROTOCOL_NAME_CMD] = extern_define.PROTOCOL_CMD_BREATHE;
                                    Log.i("log", "UDPSend 呼吸包");
                                    break;
                                case extern_define.UDPSENDSTAIRSLIGHTSET: //楼道灯光打开
                                    data1[extern_define.PROTOCOL_NAME_DESTADDR] = extern_define.PROTOCOL_LOCAT_STAIRS;
                                    data1[extern_define.PROTOCOL_NAME_DESTCHANNEL] = extern_define.PROTOCOL_STAIRS_MOSCHANNEL1_LIGHT;
                                    data1[extern_define.PROTOCOL_NAME_CMD] = extern_define.PROTOCOL_CMD_MOSSET;
                                    data1[extern_define.PROTOCOL_NAME_CMD+1] = extern_define.PROTOCOL_LIGHT_OPEN;
                                    Log.i("log", "UDPSend 楼道灯光打开");
                                    break;
                                case extern_define.UDPSENDSTAIRSLIGHTRESET: //楼道灯光关闭
                                    data1[extern_define.PROTOCOL_NAME_DESTADDR] = extern_define.PROTOCOL_LOCAT_STAIRS;
                                    data1[extern_define.PROTOCOL_NAME_DESTCHANNEL] = extern_define.PROTOCOL_STAIRS_MOSCHANNEL1_LIGHT;
                                    data1[extern_define.PROTOCOL_NAME_CMD] = extern_define.PROTOCOL_CMD_MOSSET;
                                    data1[extern_define.PROTOCOL_NAME_CMD+1] = extern_define.PROTOCOL_LIGHT_CLOSE;
                                    Log.i("log", "UDPSend 楼道灯光关闭");
                                    break;
                                case extern_define.UDPSENDOUTTWOLIGHTSET: //二楼外侧灯光打开
                                    data1[extern_define.PROTOCOL_NAME_DESTADDR] = extern_define.PROTOCOL_LOCAT_TWOOUT;
                                    data1[extern_define.PROTOCOL_NAME_DESTCHANNEL] = extern_define.PROTOCOL_OUTTWO_MOSCHANNEL1_LIGHT;
                                    data1[extern_define.PROTOCOL_NAME_CMD] = extern_define.PROTOCOL_CMD_MOSSET;
                                    data1[extern_define.PROTOCOL_NAME_CMD+1] = extern_define.PROTOCOL_LIGHT_OPEN;
                                    Log.i("log", "UDPSend 二楼外侧灯光打开");
                                    break;
                                case extern_define.UDPSENDOUTTWOLIGHTRESET:   //二楼外侧灯光关闭
                                    data1[extern_define.PROTOCOL_NAME_DESTADDR] = extern_define.PROTOCOL_LOCAT_TWOOUT;
                                    data1[extern_define.PROTOCOL_NAME_DESTCHANNEL] = extern_define.PROTOCOL_OUTTWO_MOSCHANNEL1_LIGHT;
                                    data1[extern_define.PROTOCOL_NAME_CMD] = extern_define.PROTOCOL_CMD_MOSSET;
                                    data1[extern_define.PROTOCOL_NAME_CMD+1] = extern_define.PROTOCOL_LIGHT_CLOSE;
                                    Log.i("log", "UDPSend 二楼外侧灯光关闭");
                                    break;
                                case extern_define.UDPSENDTWOBEDROOMLIGHTSET: //二楼卧室灯光打开
                                    data1[extern_define.PROTOCOL_NAME_DESTADDR] = extern_define.PROTOCOL_LOCAL_TWOSLEEP;
                                    data1[extern_define.PROTOCOL_NAME_DESTCHANNEL] = extern_define.PROTOCOL_TWOBED_MOSCHANNEL1_LIGHT;
                                    data1[extern_define.PROTOCOL_NAME_CMD] = extern_define.PROTOCOL_CMD_MOSSET;
                                    data1[extern_define.PROTOCOL_NAME_CMD+1] = extern_define.PROTOCOL_LIGHT_OPEN;
                                    Log.i("log", "UDPSend 二楼卧室灯光打开");
                                    break;
                                case extern_define.UDPSENDTWOBEDROOMLIGHTRESET:   //二楼卧室灯光关闭
                                    data1[extern_define.PROTOCOL_NAME_DESTADDR] = extern_define.PROTOCOL_LOCAL_TWOSLEEP;
                                    data1[extern_define.PROTOCOL_NAME_DESTCHANNEL] = extern_define.PROTOCOL_TWOBED_MOSCHANNEL1_LIGHT;
                                    data1[extern_define.PROTOCOL_NAME_CMD] = extern_define.PROTOCOL_CMD_MOSSET;
                                    data1[extern_define.PROTOCOL_NAME_CMD+1] = extern_define.PROTOCOL_LIGHT_CLOSE;
                                    Log.i("log", "UDPSend 二楼卧室灯光关闭");
                                    break;
                                default:
                                    break;
                            }
                            data1[extern_define.PROTOCOL_NAME_CRC8] = CheckSum8(data1);
                            sendBuf = getBytes(data1);
                            InetAddress serverAddress = InetAddress.getByName(getString(R.string.network_ip_addr));
                            DatagramPacket packetS = new DatagramPacket(sendBuf, sendBuf.length, serverAddress, Integer.parseInt(getString(R.string.network_desc_port)));
                            for(int i=0;i<3;i++) {
                                socketUDP.send(packetS);    //循环发送3次
                                Thread.sleep(300);
                            }
                        }catch(Exception e) {
                            Log.i("log", "sendMsg Error:" + e.toString());
                        }
                    }
                };
                Looper.loop();
            }
        }
    };

    private Runnable timeHandleFunc = new Runnable() {
        private int packSendDelay=extern_define.PACKSENDDELAY;       //呼吸包发送间隔时间计数
        @Override
        public void run() {
            try {
                Thread.sleep(3000);
            }catch(Exception e)
            {
                Log.i("DEBUG", "Thread.sleep try error " + e.toString());
            }
            while(true) {
                /*----------------------------------节点设备响应时间延迟----------------------------------------------*/
                if (inDoorIntCount != 0) inDoorIntCount--;
                if (stairsIntCount != 0) {
                    stairsIntCount--;
                    if(stairsIntCount == 1)
                    {
                        Message todeviceLightSet = new Message();
                        todeviceLightSet.arg1 = extern_define.UDPSENDSTAIRSLIGHTRESET;
                        deviceLightSet.sendMessageDelayed(todeviceLightSet, 0);
                    }
                }
                if (twoBedIntCount != 0){
                    twoBedIntCount--;
                    if(twoBedIntCount == 1)
                    {
                        Message todeviceLightSet = new Message();
                        todeviceLightSet.arg1 = extern_define.UDPSENDTWOBEDROOMLIGHTRESET;
                        deviceLightSet.sendMessageDelayed(todeviceLightSet, 0);
                    }
                }
                if (twoOutIntCount != 0) twoOutIntCount--;
                if(twoOutIntCount == 1)
                {
                    Message todeviceLightSet = new Message();
                    todeviceLightSet.arg1 = extern_define.UDPSENDOUTTWOLIGHTRESET;
                    deviceLightSet.sendMessageDelayed(todeviceLightSet, 0);
                }

                if (packSendDelay  != 0) packSendDelay--;
                else{
                    packSendDelay = extern_define.PACKSENDDELAY;
                    Message toUdpSendHandle1 = new Message();
                    toUdpSendHandle1.arg1 = extern_define.UDPSENDBREATHEPACK;
                    udpSendHandler.sendMessage(toUdpSendHandle1);
                }
                /*--------------------------------设备在线状态倒计时-------------------------------------*/
                if(doorOnlyCount != 0){
                    doorOnlyCount--;
                    if(doorOnlyCount == 1)
                    {
                        Message DeviceOnlySetHandle = new Message();
                        DeviceOnlySetHandle.arg1 = extern_define.DOORDEVICECHECKBOXRESET;
                        deviceOnlyCheckBoxSet.sendMessage(DeviceOnlySetHandle);
                    }
                }
                if(stairsOnlyCount != 0){
                    stairsOnlyCount--;
                    if(stairsOnlyCount == 1)
                    {
                        Message DeviceOnlySetHandle = new Message();
                        DeviceOnlySetHandle.arg1 = extern_define.STAIRSDEVICECHECKBOXRESET;
                        deviceOnlyCheckBoxSet.sendMessage(DeviceOnlySetHandle);
                    }
                }
                if(outTwoOnlyCount != 0){
                    outTwoOnlyCount--;
                    if(outTwoOnlyCount == 1)
                    {
                        Message DeviceOnlySetHandle = new Message();
                        DeviceOnlySetHandle.arg1 = extern_define.OUTTWODEVICECHECKBOXRESET;
                        deviceOnlyCheckBoxSet.sendMessage(DeviceOnlySetHandle);
                    }
                }
                if(twoBedOnlyCount != 0){
                    twoBedOnlyCount--;
                    if(twoBedOnlyCount == 1)
                    {
                        Message DeviceOnlySetHandle = new Message();
                        DeviceOnlySetHandle.arg1 = extern_define.TWOBEDROOMDEVICECHECKBOXRESET;
                        deviceOnlyCheckBoxSet.sendMessage(DeviceOnlySetHandle);
                    }
                }
                /*更新TEXTVIEW文本*/
                try {
                    text_infoHandler.sendEmptyMessage(0);
                    Thread.sleep(1000);
                }catch(Exception e)
                {
                    Log.i("DEBUG", "Thread.sleep try error " + e.toString());
                }
            }
        }
    };

    /*在线设备状态更新*/
    Handler deviceOnlyCheckBoxSet = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.arg1 == extern_define.DOORDEVICECHECKBOXSET) {
                doorOnlyCB.setChecked(true);
            }
            if(msg.arg1 == extern_define.STAIRSDEVICECHECKBOXSET)
            {
                stairsOnlyCB.setChecked(true);
            }
            if(msg.arg1 == extern_define.OUTTWODEVICECHECKBOXSET)
            {
                outTwoOnlyCB.setChecked(true);
            }
            if(msg.arg1 == extern_define.TWOBEDROOMDEVICECHECKBOXSET)
            {
                twoBedroomOnlyCB.setChecked(true);
            }

            if (msg.arg1 == extern_define.DOORDEVICECHECKBOXRESET) {
                doorOnlyCB.setChecked(false);
            }
            if(msg.arg1 == extern_define.STAIRSDEVICECHECKBOXRESET)
            {
                stairsOnlyCB.setChecked(false);
            }
            if(msg.arg1 == extern_define.OUTTWODEVICECHECKBOXRESET)
            {
                outTwoOnlyCB.setChecked(false);
            }
            if(msg.arg1 == extern_define.TWOBEDROOMDEVICECHECKBOXRESET)
            {
                twoBedroomOnlyCB.setChecked(false);
            }
        }
    };

    /*灯光开关状态更新*/
    Handler deviceLightSet = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            /*二楼外侧*/
            if (msg.arg1 == extern_define.UDPSENDOUTTWOLIGHTSET) {
                outTwoLightSwitch.setChecked(true);
            }
            if(msg.arg1 == extern_define.UDPSENDOUTTWOLIGHTRESET)
            {
                outTwoLightSwitch.setChecked(false);
            }
            /*楼道*/
            if (msg.arg1 == extern_define.UDPSENDSTAIRSLIGHTSET) {
                stairsLightSwitch.setChecked(true);
            }
            if(msg.arg1 == extern_define.UDPSENDSTAIRSLIGHTRESET)
            {
                stairsLightSwitch.setChecked(false);
            }
            /*二楼卧室*/
            if (msg.arg1 == extern_define.UDPSENDTWOBEDROOMLIGHTSET) {
                twoBedroomLightSwitch.setChecked(true);
            }
            if(msg.arg1 == extern_define.UDPSENDTWOBEDROOMLIGHTRESET)
            {
                twoBedroomLightSwitch.setChecked(false);
            }
        }
    };


    /*textinfo文本更新*/
    Handler text_infoHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            try {
                info_text.setText(      "门口人体感应         " + Integer.toString(doorTrigCount)
                                    + "\n楼道人体感应         " + Integer.toString(stairsTrigCount)
                                    + "\n卧室人体感应         " + Integer.toString(twoBedTrigCount)
                                    + "\n二外人体感应         " + Integer.toString(outTwoTrigCount));
                Log.i("TEXT", "更新 TEXT_INFO 门口" + Integer.toString(doorTrigCount));
            }catch (Exception e)
            {
                Log.i("ERROR", "info_text.setText try error " + e.toString());
            }

            /*-------------------------------世界时间显示更新-------------------------------------*/
            try {
                SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日    HH:mm:ss");
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                String str = formatter.format(curDate);
                time_text.setText("" + str);
                Log.i("TEXT", "更新 TEXT_INFO 时间" + str);

                Calendar c = Calendar.getInstance();
                /*判断整点*/
                if(current_hour != c.get(Calendar.HOUR_OF_DAY)) {
                    current_hour = c.get(Calendar.HOUR_OF_DAY);
                    /*每天23：00 把当天的设备触发计数清零*/
                    if(current_hour == 23) {
                        doorTrigCount=0;
                        stairsTrigCount=0;
                        outTwoTrigCount=0;
                        twoBedTrigCount=0;
                    }
                    /*早上6点到晚上9点提供语音服务*/
                    if(current_hour >=6 && current_hour <= 21)
                    {
                        if(current_hour >=8 && current_hour <= 20) {
                            mTts.startSpeaking("整点报时：现在时间：" + c.get(Calendar.HOUR) + "点整。", mSynListener);
                            Log.i("TEXT", "整点报时");
                        }
                        if(current_hour == 6)
                        {
                            mTts.startSpeaking("现在时间是早上6点钟，每一个早晨，都是美丽的开始！ ", mSynListener);
                            Message toMusicHandle = new Message();
                            toMusicHandle.arg1 = extern_define.PROTOCOL_MUSIC_YZCW;
                            musicHandler.sendMessage(toMusicHandle);
                            Log.i("TEXT", "早上好");
                        }
                        if(current_hour == 7)
                        {
                             /*注意 同一时间讯飞语音播放只能一处调用，否则会导致异常*/
                            Message toMusicHandle = new Message();
                            toMusicHandle.arg1 = extern_define.PROTOCOL_GET_WEATHER;
                            musicHandler.sendMessage(toMusicHandle);
                            Log.i("TEXT", "天气播报");
                        }
                        if(current_hour == 21)
                        {
                            Message toMusicHandle = new Message();
                            toMusicHandle.arg1 = extern_define.PROTOCOL_MUSIC_GOHOME;
                            musicHandler.sendMessage(toMusicHandle);
                            mTts.startSpeaking("现在是晚上9点整，晚上好，今天门口感应器触发了  "+doorTrigCount+"，次," +
                                                "楼道感应器触发了" + stairsTrigCount + "，次，" +
                                                "二楼卧室感应器触发了" + twoBedTrigCount + "，次，" +
                                                "二楼外侧感应器触发了" + outTwoTrigCount + "，次，" +
                                                "晚上9点到第二天6点将不再进行语音播报", mSynListener);
                            Log.i("TEXT", "晚上播报");
                        }
                    }

                }
            }catch (Exception e)
            {
                Log.i("ERROR", "timeDisplayHandle Error:" + e.toString());
            }
        }
    };
    //退出提示
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            AlertDialog alertDialog = new AlertDialog.Builder(
                    MainActivity.this).setTitle("退出程序").setMessage("是否退出程序")
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    android.os.Process.killProcess(
                                            android.os.Process.myPid());
                                }

                            })
                    .setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    return;
                                }
                            }).create(); // 创建对话框

            alertDialog.show();  // 显示对话框

            return false;
        }

        return false;
    }

    //CRC8 检验和
    private char CheckSum8(char[] buffer)
    {
        int crc8=0;
        for (int j = 0; j < buffer.length-1; j++)
        {
            crc8 += buffer[j];
        }
        return (char)(crc8&0xFF);
    }

    // char转byte
    private byte[] getBytes (char[] chars) {
        byte handleBuf[] = new byte[11];
        int temp;
        for (int j = 0; j < chars.length; j++)
        {
            temp = chars[j];
            if(temp > 128){
                handleBuf[j] = (byte)(temp-256);
            }else{
                handleBuf[j] = (byte)temp;
            }
        }
        return handleBuf;
    }
}
